package java6699.generic;

import java.util.*;

/**
 * @program: java_zzx
 * @description: 统计字符串中每个字符出现的次数
 * @author: zzx
 * @create: 2022-10-11 17:45
 **/
public class Counter6699 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入字符串：");
        String line = sc.nextLine();
        System.out.print("包含：");
        count6699(line).forEach(Counter6699::print);
    }
    public static List<Map.Entry> count6699(String str){
        Map<Character, Integer> tm = new TreeMap<>();
        char[] chars = str.toCharArray();
        for (char ch : chars) {
            // tm.compute(ch,Counter6699::add);
            tm.merge(ch,1,Integer::sum);
        }
        List<Map.Entry> list = new ArrayList<>(tm.entrySet());
        list.sort(new Sort());
        return list;
    }
    public static class Sort implements Comparator<Map.Entry>{

        @Override
        public int compare(Map.Entry o1, Map.Entry o2) {
            //第一次  次数降序
            int sort1 = Integer.compare((int)o2.getValue(),(int)o1.getValue());
            //第二次  字符升序
            return sort1 == 0?Character.compare((char)o1.getKey(),(char)o2.getKey()):sort1;
        }
    }
    //此方法为输出
    private static void print(Map.Entry entry) {
        System.out.print("字符" + entry.getKey() + "=" + entry.getValue()+" ");
    }
}
